package com.bangdream.michelia.view.fragment.main.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.andview.refreshview.XRefreshView;
import com.bangdream.michelia.R;
import com.bangdream.michelia.contract.CoursesContract;
import com.bangdream.michelia.contract.LiveContract;
import com.bangdream.michelia.contract.RecommendContract;
import com.bangdream.michelia.entity.CommentBean;
import com.bangdream.michelia.entity.LearningStateBean;
import com.bangdream.michelia.entity.LiveUrlBean;
import com.bangdream.michelia.entity.RxEventBean;
import com.bangdream.michelia.entity.courses.CoursesBean;
import com.bangdream.michelia.entity.CoursesTypeBean;
import com.bangdream.michelia.entity.LiveBean;
import com.bangdream.michelia.entity.RecommendBean;
import com.bangdream.michelia.presenter.CoursesPresenter;
import com.bangdream.michelia.presenter.LivePersenter;
import com.bangdream.michelia.presenter.RecommendPresenter;
import com.bangdream.michelia.tool.FullyGridLayoutManager;
import com.bangdream.michelia.tool.FullyLinearLayoutManager;
import com.bangdream.michelia.tool.ZoomOutPageTransformer;
import com.bangdream.michelia.tool.glide.BannerGlideImageLoader;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.PublicUtil;
import com.bangdream.michelia.utils.RxBus;
import com.bangdream.michelia.view.activity.currency.MainActivity;
import com.bangdream.michelia.view.activity.curriculum.CourseListActivity;
import com.bangdream.michelia.view.activity.live.LiveDetails;
import com.bangdream.michelia.view.activity.my.LearningRecords;
import com.bangdream.michelia.view.activity.my.MyCollection;
import com.bangdream.michelia.view.adapter.CurriculumGridItemAdapter;
import com.bangdream.michelia.view.adapter.CurriculumItemAdapter;
import com.bangdream.michelia.view.adapter.CurriculumVideoGridItemAdapter;
import com.bangdream.michelia.view.adapter.viewpage.InfoPageAdapter;
import com.bangdream.michelia.view.fragment.currency.LazyLoadFragment;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.util.List;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * @date on 2018/6/18 23:36
 * @email 909732184@qq.com
 * 学习中心
 */
public class HomeLearningCenter extends LazyLoadFragment<CoursesContract.ICoursesView,CoursesPresenter<CoursesContract.ICoursesView>>
        implements View.OnClickListener,CoursesContract.ICoursesView,LiveContract.ILiveView,RecommendContract.IRecommendView,CoursesContract.ILearningState{
    private View view;
    //头部广告栏
    private Banner bannerView;
    //显示个人信息的滑动viewpage
    private ViewPager infoViewPage;
    private XRefreshView refreshView;
    //推荐课程 普通课程 直播课程的列表展示recyclerView
    private RecyclerView recyclerRecommendCurriculum,recyclerOrdinaryCurriculum,recyclerVideoCurriculum;
    //普通课程网格布局
    private CurriculumGridItemAdapter curriculumGridAdapter;
    //普通课程列表布局
    private CurriculumItemAdapter curriculumItemAdapter;
    //直播课程网格布局
    private CurriculumVideoGridItemAdapter liveAdapter;
    //垂直和网格的recylervwe 布局模式
    private FullyLinearLayoutManager layoutManager;
    private FullyGridLayoutManager gridLayoutManager1,gridLayoutManager2;
    private LinearLayout btnLearningRecords,btnMyCollection,btnFreeAdmission,btnNewRecommend;
    private TextView tv_recommend_more,tv_all_more,tv_live_more;
    //直播服务
    private LivePersenter<LiveContract.ILiveView> livePersenter;

    //头部广告栏推荐
    private RecommendPresenter<RecommendContract.IRecommendView> recommendPresenter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_learning_center_layout,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        setListener();
        operateBus();
    }

    @Override
    public CoursesPresenter createPresenter() {
        CoursesPresenter coursesPresenter = new CoursesPresenter();
        return coursesPresenter;
    }

    @Override
    public void loadData() {
        getData();
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void setListener() {
        btnLearningRecords.setOnClickListener(this);
        btnMyCollection.setOnClickListener(this);
        btnFreeAdmission.setOnClickListener(this);
        btnNewRecommend.setOnClickListener(this);
        tv_live_more.setOnClickListener(this);
        tv_all_more.setOnClickListener(this);
        tv_recommend_more.setOnClickListener(this);
        liveAdapter.setOnViewItemClickListener(new CurriculumVideoGridItemAdapter.OnViewItemClickListener() {
            @Override
            public void onCurriculumItemClick(int position) {
                Intent intent = new Intent(getActivity(), LiveDetails.class);
                intent.putExtra("id",liveAdapter.getData().get(position).getId());
                intent.putExtra("count",liveAdapter.getData().get(position).getLivePersonCnt());
                intent.putExtra("name",liveAdapter.getData().get(position).getName());

                startActivity(intent);
            }
        });
    }

    private void initView() {
        recyclerRecommendCurriculum = view.findViewById(R.id.recyclerRecommendCurriculum);
        recyclerOrdinaryCurriculum = view.findViewById(R.id.recyclerOrdinaryCurriculum);
        recyclerVideoCurriculum = view.findViewById(R.id.recyclerVideoCurriculum);
        btnFreeAdmission = view.findViewById(R.id.btnFreeAdmission);
        btnNewRecommend = view.findViewById(R.id.btnNewRecommend);
        tv_recommend_more = view.findViewById(R.id.tv_recommend_more);
        tv_all_more = view.findViewById(R.id.tv_all_more);
        tv_live_more = view.findViewById(R.id.tv_live_more);
        bannerView = view.findViewById(R.id.banner);
        ViewGroup.LayoutParams layoutParams = bannerView.getLayoutParams();
        layoutParams.height = (int)(MainActivity.screenWidth*0.44);
        bannerView.setLayoutParams(layoutParams);

        refreshView = view.findViewById(R.id.refreshView);
        refreshView.setPullLoadEnable(false);
        refreshView.setPullRefreshEnable(true);
        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener(){
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                getData();
            }
        });
        infoViewPage = view.findViewById(R.id.infoViewPage);
        btnLearningRecords = view.findViewById(R.id.btnLearningRecords);
        btnMyCollection = view.findViewById(R.id.btnMyCollection);


//        setInfoViewPage(bean);
        setRecyclerViewList();
        livePersenter = new LivePersenter();
        livePersenter.attach(this);
        recommendPresenter = new RecommendPresenter<>();
        recommendPresenter.attach(this);
    }
    private void getData(){
        //获取头部推荐轮播数据

        recommendPresenter.getRecommendListData(1,4,null);
        //推荐课程显示课程列表的前4条数据
        mPresenter.getCoursesListData(1,4,CoursesContract.CoursesType.Recommend,null);
        //获取首页的直播数据
        livePersenter.getLiveListData(1,10,null,null);
        //获取首页学习状态
        mPresenter.getLearningState();
    }
    private void setRecyclerViewList() {
        //网格布局分为两列
        gridLayoutManager1 = new FullyGridLayoutManager(getActivity(),2);
        gridLayoutManager2 = new FullyGridLayoutManager(getActivity(),2);
        //动态设置网格的列数 如果是第一条数据 则宽度占满两列 其余数据宽度占只1列
        gridLayoutManager2.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position==0?2:1;
            }
        });
        layoutManager = new FullyLinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager.setScrollEnabled(false);
        recyclerRecommendCurriculum.setLayoutManager(gridLayoutManager1);
        recyclerOrdinaryCurriculum.setLayoutManager(layoutManager);
        recyclerVideoCurriculum.setLayoutManager(gridLayoutManager2);
        //去掉焦点防止页面不在最顶部
        recyclerRecommendCurriculum.setFocusable(false);
        recyclerOrdinaryCurriculum.setFocusable(false);
        recyclerVideoCurriculum.setFocusable(false);
        curriculumGridAdapter = new CurriculumGridItemAdapter(getActivity());
        recyclerRecommendCurriculum.setAdapter(curriculumGridAdapter);
        curriculumItemAdapter = new CurriculumItemAdapter(getActivity());
        recyclerOrdinaryCurriculum.setAdapter(curriculumItemAdapter);
        liveAdapter = new CurriculumVideoGridItemAdapter(getActivity());
        recyclerVideoCurriculum.setAdapter(liveAdapter);
    }

    //设置显示用户信息的viewpage数据
    private void setInfoViewPage(LearningStateBean bean){
        infoViewPage.removeAllViewsInLayout();
        ViewGroup.LayoutParams layoutParams = infoViewPage.getLayoutParams();
        layoutParams.width = MainActivity.screenWidth - (PublicUtil.dip2px(mApp,30)*2);
        infoViewPage.setLayoutParams(layoutParams);

        FragmentStatePagerAdapter adapter = new InfoPageAdapter(getChildFragmentManager(),mApp, bean);

        infoViewPage.setOffscreenPageLimit(3);
        infoViewPage.setPageTransformer(true, new ZoomOutPageTransformer());
        infoViewPage.setAdapter(adapter);
        infoViewPage.setCurrentItem(1);
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.btnLearningRecords:
                intent = new Intent(getActivity(), LearningRecords.class);
                startActivity(intent);
                break;
            case R.id.btnMyCollection:
                intent = new Intent(getActivity(), MyCollection.class);
                startActivity(intent);
                break;
            case R.id.btnFreeAdmission://免费课程
                goCourseList("1");
                break;
            case R.id.btnNewRecommend://最新推荐
                goCourseList("2");
                break;
            case R.id.tv_recommend_more://推荐课程更多
                goCourseList("3");
                break;
            case R.id.tv_all_more://全部课程
                goCourseList("4");
                break;
            case R.id.tv_live_more://全部直播
                Intent intent2 = new Intent(getActivity(), MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("flagIndex", 3);
                intent2.putExtras(bundle);
                startActivity(intent2);
                break;
            default:
                break;
        }
    }

    private void goCourseList(String type){
        Intent intent=new Intent(getActivity(),CourseListActivity.class);
        intent.putExtra("courseType",type);
        startActivity(intent);
    }

    @Override
    public void setCoursestList(boolean isSuccess, int page, CoursesContract.CoursesType type, List<CoursesBean> data, String stDescribe) {
        //推荐课程
        if(type == CoursesContract.CoursesType.Recommend){
//            if(data!=null){
                curriculumGridAdapter.setData(data);
                curriculumGridAdapter.notifyDataSetChanged();
//            }
            //推荐课程请求完之后再去取普通课程
            //普通课程列表展示6条数据
            mPresenter.getCoursesListData(1,6,CoursesContract.CoursesType.Ordinary,null);
        }else {
            //普通课程
//            if(data!=null){
                curriculumItemAdapter.setData(data);
                curriculumItemAdapter.notifyDataSetChanged();
//            }
        }
    }

    @Override
    public void setCoursesDetails(boolean isSuccess, CoursesBean data, String stDescribe) {

    }

    @Override
    public void setCoursesTypeList(boolean isSuccess, List<CoursesTypeBean> data, String stDescribe) {
            L.d("setCoursesTypeList"+data.toString());
    }

    @Override
    public void setCommentList(boolean isSuccess, int page, List<CommentBean> data, String stDescribe) {

    }

    @Override
    public void actionComment(boolean isSuccess, String stDescribe) {

    }

    @Override
    public void setLiveList(boolean isSuccess, int page, List<LiveBean> data, String stDescribe) {
        if(isSuccess){
            liveAdapter.setData(data);
            liveAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setLiveDetails(boolean isSuccess, LiveBean data, String stDescribe) {

    }

    @Override
    public void setLiveUrl(boolean isSuccess, List<String> url) {

    }

    @Override
    public void setRePlayLiveUrl(boolean isSuccess, List<String> url) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(livePersenter!=null)
            livePersenter.detach();
        if(recommendPresenter!=null)
            recommendPresenter.detach();
    }

    @Override
    public void setRecommendList(boolean isSuccess, int page, final List<RecommendBean> data, String stDescribe) {
        refreshView.stopRefresh();
        if(isSuccess) {
            if(null!=data){
                //设置图片加载器
                bannerView.setImageLoader(new BannerGlideImageLoader());
                //设置图片集合
                bannerView.setImages(data);
                //设置自动轮播间隔
                bannerView.setDelayTime(5000);
                bannerView.setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        Uri uri = Uri.parse(data.get(position).getHref());
                        Intent it = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(it);
                    }
                });
                //banner设置方法全部调用完毕时最后调用
                bannerView.start();
            }

        }
    }



    @Override
    public void setLearningState(boolean isSuccess, LearningStateBean bean) {
        if(isSuccess){
            setInfoViewPage(bean);
        }else{
//            setInfoViewPage(new LearningStateBean());

        }
    }

    @SuppressLint("CheckResult")
    public void operateBus() {
        disposable = RxBus.getInstance().toObservable().map(new Function<Object, RxEventBean>() {
            @Override
            public RxEventBean apply(Object o) throws Exception {
                return (RxEventBean) o;
            }
        }).subscribe(new Consumer<RxEventBean>() {
            @Override
            public void accept(RxEventBean bean) throws Exception {

                if(bean.getCode()==0x02){
                    refreshView.startRefresh();
                }
            }
        });
    }
}
